#include "Viewport.h"

void Viewport::pan(Vector2 deltaPos)
{
	this->pos.x -= (deltaPos.x / this->zoom);
	this->pos.y -= (deltaPos.y / this->zoom);
}

bool Viewport::isPointInViewport(float x, float y)
{
	Vector2 objectPos = this->gameworldToScreen(x, y);

	if (objectPos.x < 0) // point left of viewport
		return false;
	if (objectPos.y < 0) // point right of viewport
		return false;
	if (objectPos.x > this->size.x) // point above viewport
		return false;
	if (objectPos.y > this->size.y) // point underneath viewport
		return false;
	
	// point in viewport
	return true;
}
bool Viewport::isPointInViewport(Vector2 point)
{
	return Viewport::isPointInViewport(point.x, point.y);
}

bool Viewport::isRectInViewport(float x1, float y1, float x2, float y2)
{
	if (isPointInViewport(x1, y1)) // UpperLeft
		return true;
	if (isPointInViewport(x1, y2)) // UpperRight
		return true;
	if (isPointInViewport(x2, y1)) // LowerLeft
		return true;
	if (isPointInViewport(x2, y2)) // LowerRight
		return true;

	// no corner inside viewport
	return false;
}
bool Viewport::isRectInViewport(Rectangle2 rect)
{
	return Viewport::isRectInViewport(rect.x, rect.y, rect.x + rect.width * this->zoom, rect.y + rect.height * this->zoom);
}

bool Viewport::isTileInViewport(int tileX, int tileY)
{
	Tile t;
	int tileSize = t.size() * this->zoom;

	return isRectInViewport(tileX * tileSize, tileY * tileSize, (tileX + 1) * tileSize, (tileY + 1) * tileSize);
}

void Viewport::changeZoom(float zoom)
{
	if (zoom > 0.0f && this->zoom < 10.0f)
	{
		this->zoom *= (zoom * 2.0f);
	} 
	else if (zoom < 0.0f && this->zoom > 0.5f)
	{
		zoom *= -1.0f;
		this->zoom /= (zoom * 2.0f);
	}
}

Vector2 Viewport::screenToGameworld(int screenX, int screenY)
{
	Vector2 gameworldPos;
	gameworldPos.x = this->pos.x + (screenX / this->zoom);
	gameworldPos.y = this->pos.y + (screenY / this->zoom);
	return gameworldPos;
}

Vector2 Viewport::gameworldToScreen(float gameworldX, float gameworldY)
{
	Vector2 screenPos;
	screenPos.x = (gameworldX - this->pos.x) * this->zoom;
	screenPos.y = (gameworldY - this->pos.y) * this->zoom;
	return screenPos;
}



void Viewport::centerTo(int x, int y)
{
	Tile t;
	/*
	this->x = x * (t.size() * zoom) - (this->width / 2.0f);
	this->y = y * (t.size() * zoom) - (this->height / 2.0f);
	*/
	this->pos.x = x  - (this->size.x / 2.0f);
	this->pos.y = y  - (this->size.y / 2.0f);
}

void Viewport::centerTo(int x, int y, float zoom)
{
	this->zoom = zoom;
	this->centerTo(x, y);
}

Viewport::Viewport(int width, int height)
{
	Viewport::pos.x = 0.0f;
	Viewport::pos.y = 0.0f;
	Viewport::zoom = 1.0f;

	Viewport::size.x = width;
	Viewport::size.y = height;
}


Viewport::~Viewport(void)
{
}
